﻿using System.Reflection;
using Command.CommunityToolkit.Attributes;
using Command.CommunityToolkit.Helpers;

namespace Command.CommunityToolkit.Commands;

public class CommandFactory
{
    [Log("运行命令")]
    public ICommand? BuildCommand(string[]? args)
    {
        if (args == null) throw new ArgumentException("请输入正确的命令和参数");
        //if (args.Length==1) args=new[] { args[0], "" };//兼容ezqc log; ezqc help补全
        ICommand? command = null;
        var assembly = Assembly.GetExecutingAssembly();
        if (!Equals(null, assembly))
        {
            var typeInfos = assembly.DefinedTypes.Where(t =>
                t.CustomAttributes.Select(r => r.AttributeType).ToList().Contains(typeof(CommandAttribute)));
            var typeInfo = typeInfos.FirstOrDefault(r => r.GetCustomAttributes(typeof(CommandAttribute)).Any(w => ((w as CommandAttribute)!).Name.Equals(args[0])));//.GetCustomAttribute(typeof(CommandAttribute)) as CommandAttribute;
            if (!Equals(typeInfo, null))
            {
                if (typeInfo.FullName != null)
                {
                    var serviceProvider = ServiceProviderHelper.GetInstance().ServiceProvider;
                    if (serviceProvider != null)
                        command = assembly.CreateInstance(typeInfo.FullName, true, BindingFlags.Default, null,
                            new object[]
                            {
                                args.Length>=2?args[1]:"",
                                serviceProvider.GetService<IQualityControl>() ??
                                throw new InvalidOperationException()
                            }, null, null) as ICommand;
                }
            }

        }
        return command;
    }
}